<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="色彩空间 像素格式描述了像素数据存储所用的格式，定义了像素在内存中的编码方式。RGB和YUV为两种经常使用的像素格式。">
<meta property="og:type" content="article">
<meta property="og:title" content="YUV">
<meta property="og:url" content="https://bqlin.github.io/posts/yuv/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="色彩空间 像素格式描述了像素数据存储所用的格式，定义了像素在内存中的编码方式。RGB和YUV为两种经常使用的像素格式。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/bqlin/image-land/raw/master/1615772067597-256abbba-34ae-452b-8070-2b4685f65386.png">
<meta property="og:image" content="https://gitee.com/bqlin/image-land/raw/master/1615772067684-94dd4489-e95f-4483-9573-7fe5c4139ecb.png">
<meta property="og:image" content="https://gitee.com/bqlin/image-land/raw/master/1615772067808-3f48509f-c288-4451-8aa1-43af153ea027.png">
<meta property="og:image" content="https://gitee.com/bqlin/image-land/raw/master/1615772067907-bf5c524e-747c-41a4-be38-cbc8a40ed36f.png">
<meta property="article:published_time" content="2021-03-15T03:34:44.000Z">
<meta property="article:modified_time" content="2021-10-28T04:26:38.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="音视频">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/bqlin/image-land/raw/master/1615772067597-256abbba-34ae-452b-8070-2b4685f65386.png">

<link rel="canonical" href="https://bqlin.github.io/posts/yuv/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>YUV | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/yuv/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          YUV
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-15 11:34:44" itemprop="dateCreated datePublished" datetime="2021-03-15T11:34:44+08:00">2021-03-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-28 12:26:38" itemprop="dateModified" datetime="2021-10-28T12:26:38+08:00">2021-10-28</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%9F%B3%E8%A7%86%E9%A2%91%E6%A6%82%E5%BF%B5/" itemprop="url" rel="index"><span itemprop="name">音视频概念</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.5k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="色彩空间">色彩空间</h2>
<p>像素格式描述了像素数据存储所用的格式，定义了像素在内存中的编码方式。RGB和YUV为两种经常使用的像素格式。</p>
<h3 id="rgb格式">RGB格式</h3>
<p>RGB图像具有三个通道R、G、B，分别对应红、绿、蓝三个分量，由三个分量的值决定颜色；通常，会给RGB图像加一个通道alpha，即透明度，于是共有四个分量共同控制颜色。</p>
<p><strong>RGB用于屏幕图像的展示。</strong></p>
<h3 id="yuv格式">YUV格式</h3>
<p>YUV颜色空间是PAL、NTSC、SCEAM三大视频标准使用的颜色空间，主要应用于视频系统。使用YUV色彩空间，后期出现的彩色电视系统和早期的黑白电视系统兼容，黑白电视机可以只处理彩色电信信号中的Y分量，而彩色电视机接收黑白电视信号并显示也没有任何问题。</p>
<p><span class="math inline">\(Y&#39;UV\)</span>、<span class="math inline">\(YUV\)</span>、<span class="math inline">\(YC_bC_r\)</span>、<span class="math inline">\(YP_bP_r\)</span>等都可以称为YUV，它们所指涉的范围，常有混淆或重叠的情况。从历史的演变来说，其中<span class="math inline">\(YUV\)</span>和<span class="math inline">\(Y&#39;UV\)</span>通常用来编码电视的模拟信号，而<span class="math inline">\(YC_bC_r\)</span>则是用来描述数字的视频信号，适合影片与图片压缩以及传输，例如MPEG、JPEG。 但在现今，YUV通常已经在计算机系统上广泛使用。</p>
<p><strong>YUV用于采集与编码。</strong></p>
<ul>
<li>YUV
<ul>
<li>Y：亮度/灰阶</li>
<li>U：色调/色度</li>
<li>V：饱和度/浓度</li>
</ul></li>
<li><span class="math inline">\(YP_bP_r\)</span>，模拟份量信号/接口
<ul>
<li>P：Paralle，并行</li>
<li>b下标：蓝</li>
<li>r下标：红</li>
</ul></li>
<li><span class="math inline">\(YC_bC_r\)</span>，数字分量信号/接口
<ul>
<li>C，Chroma：色度</li>
<li><span class="math inline">\(YC_bC_r\)</span>还可指色彩空间，<span class="math inline">\(YC_bC_r\)</span>色彩空间是YUV色彩空间的缩放和偏移版本。</li>
</ul></li>
</ul>
<p>YUV 在对照片或影片编码时，考虑到人类的感知能力，允许降低色度的带宽。YUV可以通过抛弃色差来进行带宽优化。比如yuv420格式图像相比RGB来说，要节省一半的字节大小，抛弃相邻的色差对于人眼来说，差别不大。</p>
<p>YUV颜色空间和RGB颜色空间可以根据公式相互转换。凡是渲染到屏幕上的东西，都要转换为RGB形式。</p>
<p>标清电视使用标准BT.601： <span class="math display">\[
{\left[\begin{array}{l}
Y&#39; \\
U \\
V
\end{array}\right]\\
= \left[\begin{array}{ccc}
0.299 &amp; 0.587 &amp; 0.114 \\
-0.14713 &amp; -0.28886 &amp; 0.436 \\
0.615 &amp; -0.51499 &amp; -0.10001
\end{array}\right]
\left[\begin{array}{l}
R \\
G \\
B
\end{array}\right]}
\]</span></p>
<p><span class="math display">\[
{\left[\begin{array}{l}
R \\
G \\
B
\end{array}\right]\\
= \left[\begin{array}{ccc}
1 &amp; 0 &amp; 1.13983 \\
1 &amp; -0.39465 &amp; -0.58060 \\
1 &amp; 2.03211 &amp; 0
\end{array}\right]\\
\left[\begin{array}{l}
Y&#39; \\
U \\
V
\end{array}\right]}
\]</span></p>
<p>高清电视使用标准BT.709： <span class="math display">\[
{\left[\begin{array}{l}
Y^{\prime} \\
U \\
V
\end{array}\right]=\left[\begin{array}{ccc}
0.2126 &amp; 0.7152 &amp; 0.0722 \\
-0.09991 &amp; -0.33609 &amp; 0.436 \\
0.615 &amp; -0.55861 &amp; -0.05639
\end{array}\right]\left[\begin{array}{l}
R \\
G \\
B
\end{array}\right]}
\]</span></p>
<p><span class="math display">\[
{\left[\begin{array}{l}
R \\
G \\
B
\end{array}\right]=\left[\begin{array}{ccc}
1 &amp; 0 &amp; 1.28033 \\
1 &amp; -0.21482 &amp; -0.38059 \\
1 &amp; 2.12798 &amp; 0
\end{array}\right]\left[\begin{array}{l}
Y^{\prime} \\
U \\
V
\end{array}\right]}
\]</span></p>
<p>对于iOS采集的CMSampleBufferRef，调用<code>CVBufferGetAttachment</code>获取YCbCrMatrix，决定使用BT.601还是BT.709。</p>
<h2 id="采样方式">采样方式</h2>
<p>YUV相比于RGB格式最大的好处是可以做到在保持图像质量降低不明显的前提下，减小文件大小。YUV格式之所以能够做到，是因为进行了采样操作。</p>
<p>YUV图像存储模式与采样方式密切相关。主流的采样方式有三种，YUV4:4:4<strong>(YUV444)</strong>、YUV4:2:2<strong>(YUV422)</strong>、YUV4:2:0<strong>(YUV420)</strong>（所有设备都支持）。这些采样方式，不压缩Y分量，对UV分量的压缩程度不同，这是由人眼的特性决定的，人眼对亮度Y更敏感，对色度UV没有那么敏感，压缩UV分量可以降低数据量，但并不会人眼主观感觉造成太大影响。</p>
<p>YUV后面接的数字就是<span class="math inline">\(Y\)</span>、<span class="math inline">\(C_b\)</span>、<span class="math inline">\(C_r\)</span>三个分量的比例。</p>
<p>若以以黑点表示采样该像素点的Y分量，以空心圆圈表示采用该像素点的UV分量，则这三种采样方式如下：</p>
<p><img src="https://gitee.com/bqlin/image-land/raw/master/1615772067597-256abbba-34ae-452b-8070-2b4685f65386.png" /></p>
<p>即：</p>
<ul>
<li><p>YUV4:4:4采样，每一个Y对应一组UV分量。</p></li>
<li><p>YUV4:2:2采样，每两个Y共用一组UV分量。</p></li>
<li><p>YUV4:2:0采样，每四个Y共用一组UV分量。</p></li>
</ul>
<h3 id="yuv444">YUV4:4:4</h3>
<p>4:4:4，表示完全取样。每个 Y 对应一组 UV 分量。</p>
<p><img src="https://gitee.com/bqlin/image-land/raw/master/1615772067684-94dd4489-e95f-4483-9573-7fe5c4139ecb.png" /></p>
<p>相邻的4个像素里有4个Y、4个U、4个V。每1个Y使用1组UV分量。如下(每个[]为一个像素点)：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[ Y U V ]  [ Y U V ]  [ Y U V ]  [ Y U V ]</span><br><span class="line">[ Y U V ]  [ Y U V ]  [ Y U V ]  [ Y U V ]</span><br><span class="line">[ Y U V ]  [ Y U V ]  [ Y U V ]  [ Y U V ]</span><br><span class="line">[ Y U V ]  [ Y U V ]  [ Y U V ]  [ Y U V ]</span><br></pre></td></tr></table></figure>
<p>在这种采样方式下，一个像素点包含的完整的信息。</p>
<p><strong>每个像素大小是3字节（24位），与RGB一致。</strong></p>
<h3 id="yuv422">YUV4:2:2</h3>
<p>4:2:2，表示 2:1 水平取样，垂直完全采样。每两个 Y 共用一组 UV 分量。</p>
<p><img src="https://gitee.com/bqlin/image-land/raw/master/1615772067808-3f48509f-c288-4451-8aa1-43af153ea027.png" /></p>
<p>相邻的4个像素里有4个Y、2个U、2个V。每2个Y共用1组UV分量。平均算来，一个像素占用的数据宽度为16b，其中Y占8b，U占4b，V占4b。后面存储模式命名中的数字16指的就是16b。<strong>平均每个像素大小是2字节，比RGB少⅓。</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[ Y U ]  [ Y V ]  [ Y U ]  [ Y V ]</span><br><span class="line">[ Y V ]  [ Y U ]  [ Y V ]  [ Y U ]</span><br><span class="line">[ Y U ]  [ Y V ]  [ Y U ]  [ Y V ]</span><br><span class="line">[ Y V ]  [ Y U ]  [ Y V ]  [ Y U ]</span><br></pre></td></tr></table></figure>
<p>在这种采样方式下，还原出一个像素点，需要相邻的两个像素点数据，如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[ Y U ]  [ Y V ]</span><br></pre></td></tr></table></figure>
<h3 id="yuv420">YUV4:2:0</h3>
<p>4:2:0，表示 2:1 水平取样，垂直 2:1 采样。</p>
<p><img src="https://gitee.com/bqlin/image-land/raw/master/1615772067907-bf5c524e-747c-41a4-be38-cbc8a40ed36f.png" /></p>
<p>4:1:0并不意味着只有<span class="math inline">\(Y\)</span>、<span class="math inline">\(C_b\)</span>两个分量，而没有<span class="math inline">\(C_r\)</span>分量。实际指的是对每行扫描线来说，只有一中色度分量，相邻的扫描线存储不同的色度分量。</p>
<p>相邻的4个像素里有4个Y、2个U、0个V，或4个Y、2个V，0个U。每4个Y共用1组UV分量。平均算来，一个像素占用的数据宽度为12bit，其中Y占8bit，U占2bit，V占2bit。后面存储模式命名中的数字12指的就是12b。<strong>平均每个像素是12b，比RGB少½。</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[ Y U ]  [ Y ]  [ Y U ]  [ Y ]</span><br><span class="line">[ Y V ]  [ Y ]  [ Y V ]  [ Y ]</span><br><span class="line">[ Y U ]  [ Y ]  [ Y U ]  [ Y ]</span><br><span class="line">[ Y V ]  [ Y ]  [ Y V ]  [ Y ]</span><br></pre></td></tr></table></figure>
<p>在这种采样方式下，还原出一个像素点，需要相邻的四个像素点数据，如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[ Y U ]  [ Y ]</span><br><span class="line">[ Y V ]  [ Y ]</span><br></pre></td></tr></table></figure>
<p><span class="math display">\[
YUV4:2:0 数据量 = Y × 1.5 = RGB ÷ 2
\]</span></p>
<h2 id="存储格式">存储格式</h2>
<p>在同一采样模式下，根据分量元素排列顺序的不同，又分为不同的存储模式。</p>
<ul>
<li><p><strong>packed</strong>，紧缩格式（packed formats）：将 Y、U、V 值存储成一个 Macro Pixels 数组，和 RGB 的存放方式类似。</p>
<ul>
<li><p>内存中排列形式类似：YVYUYVYUYVYUYVYU...。</p></li>
<li><p>在具体的存储模式命名中，packed格式不带后缀P。</p></li>
<li><p>适合YUV 4:4:4</p></li>
</ul></li>
<li><p><strong>planar</strong>，平面格式（planar formats）：将 Y、U、V 3个分量分别存放在不同的矩阵中（3个字节数组）。</p>
<ul>
<li><p>内存中排列形式类似：YYYYYY...，UUUUUU...，VVVVVV...。</p></li>
<li><p>在具体的存储模式命名中，planar格式带后缀P。</p></li>
<li><p>适合I420（YUV420p）、YV12（YUV420p）</p></li>
</ul></li>
<li><p><strong>semi-planar</strong>，将Y、U、V三个分量放在2个矩阵(平面)中（2个字节数组）。Y占用一个平面，UV共用一个平面。</p></li>
<li><p>内存中排列形式类似：YYYYYY...，UVUVUV...。</p>
<ul>
<li>在具体的存储模式命名中，semi-planar格式带后缀SP。</li>
</ul></li>
<li><p>适合NV12（YUV420sp）、NV21（YUV420sp）</p></li>
</ul>
<h2 id="像素格式">像素格式</h2>
<h3 id="yuv422-1">YUV422</h3>
<p>内存分布：YUYV、YVYU、UYVY、VYUY</p>
<p>这四种格式每一种又可以分为2类（packed和planar），以<strong>YUYV</strong>为例，一个6*4的图像的存储方式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Y Y Y Y Y Y                   </span><br><span class="line">Y Y Y Y Y Y                  </span><br><span class="line">Y Y Y Y Y Y                   </span><br><span class="line">Y Y Y Y Y Y                    </span><br><span class="line">U U U U U U                  Y U Y V Y U Y V Y U Y V</span><br><span class="line">U U U U U U                  Y U Y V Y U Y V Y U Y V</span><br><span class="line">V V V V V V                  Y U Y V Y U Y V Y U Y V</span><br><span class="line">V V V V V V                  Y U Y V Y U Y V Y U Y V</span><br><span class="line">- Planar -                          - Packed -</span><br></pre></td></tr></table></figure>
<h3 id="yuv420-1">YUV420</h3>
<ul>
<li>YUV420p：I420、YV12，planar，分别存储在三个字节数组中。</li>
<li>YUV420sp：NV12、NV21，semi-planar，Y存储在一个数组中，UV存储在一个数组中。</li>
</ul>
<p>同样，对于一个6*4的图像，这四种像素格式的存储方式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y</span><br><span class="line">Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y</span><br><span class="line">Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y</span><br><span class="line">Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y      Y Y Y Y Y Y</span><br><span class="line">U U U U U U      V V V V V V      U V U V U V      V U V U V U</span><br><span class="line">V V V V V V      U U U U U U      U V U V U V      V U V U V U</span><br><span class="line"> - I420 -         - YV12 -         - NV12 -         - NV21 -</span><br></pre></td></tr></table></figure>
<h2 id="占用字节数">占用字节数</h2>
<p>YUV420图像占用字节数为 ：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">size = width * height + (width * height) / 4 + (width * height) / 4 = width * height * 1.5 // 刚好是 RGB 的一半</span><br></pre></td></tr></table></figure>
<p>RGB格式的图像占用字节数为:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">size = width * height * 3</span><br></pre></td></tr></table></figure>
<p>RGBA格式的图像占用字节数为:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">size = width * height * 4</span><br></pre></td></tr></table></figure>
<h2 id="yuv数据访问">YUV数据访问</h2>
<p>对于一个YUV格式存放的文件，可以直接读取并分离成Y、U、V各个分量的文件：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 读取YUV420P的文件，每个Y、U、V值都是用一个字节存储，所以使用刚好是一字节大小的char表示</span></span><br><span class="line"><span class="type">int</span> yuv_size = w * h * <span class="number">3</span> / <span class="number">2</span>;</span><br><span class="line"><span class="type">unsigned</span> <span class="type">char</span> *pic = (<span class="type">unsigned</span> <span class="type">char</span> *)<span class="built_in">malloc</span>(yuv_size);</span><br><span class="line">fread(pic, <span class="number">1</span>, yuv_size, fyuv);</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> written_byte, writting_byte = <span class="number">0</span>;</span><br><span class="line"><span class="comment">// Y</span></span><br><span class="line">writting_byte = w * h;</span><br><span class="line">fwrite(pic + written_byte, <span class="number">1</span>, writting_byte, fy);</span><br><span class="line">written_byte += writting_byte;</span><br><span class="line"><span class="comment">// U</span></span><br><span class="line">writting_byte = w * h / <span class="number">4</span>;</span><br><span class="line">fwrite(pic + written_byte, <span class="number">1</span>, writting_byte, fu);</span><br><span class="line">written_byte += writting_byte;</span><br><span class="line"><span class="comment">// V</span></span><br><span class="line">writting_byte = w * h / <span class="number">4</span>;</span><br><span class="line">fwrite(pic + written_byte, <span class="number">1</span>, writting_byte, fv);</span><br><span class="line">written_byte += writting_byte;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对于YUV444P的分离也是类似，只是：</span></span><br><span class="line"><span class="comment">// yuv_size = w * h * 3</span></span><br><span class="line"><span class="comment">// writting_byte = w * h</span></span><br></pre></td></tr></table></figure>
<p>对于YUV格式数据变成灰度图也很简单，只需要把U、V值都置空即可：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 读取YUV420P的文件</span></span><br><span class="line"><span class="type">int</span> yuv_size = w * h * <span class="number">3</span> / <span class="number">2</span>;</span><br><span class="line"><span class="type">unsigned</span> <span class="type">char</span> *pic = (<span class="type">unsigned</span> <span class="type">char</span> *)<span class="built_in">malloc</span>(yuv_size);</span><br><span class="line">fread(pic, <span class="number">1</span>, yuv_size, fyuv);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Gray</span></span><br><span class="line"><span class="built_in">memset</span>(pic + w * h, <span class="number">0</span>, w * h / <span class="number">2</span>);</span><br><span class="line">fwrite(pic, <span class="number">1</span>, yuv_size, fyuv);</span><br></pre></td></tr></table></figure>
<h2 id="ios相机支持输出图片格式">iOS相机支持输出图片格式</h2>
<ul>
<li><p>420v</p>
<ul>
<li><p><code>kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange</code></p></li>
<li><p>表示输出的视频格式为NV12（YUV420sp）</p></li>
<li><p>范围：(luma = [16,235], chroma = [16,240])</p></li>
</ul></li>
<li><p>420f</p>
<ul>
<li><p><code>kCVPixelFormatType_420YpCbCr8BiPlanarFullRange</code></p></li>
<li><p>表示输出的视频格式为NV12（YUV420sp）</p></li>
<li><p>范围：(luma = [0,255], chroma = [1,255])</p></li>
</ul></li>
<li><p>BGRA</p>
<ul>
<li><code>kCVPixelFormatType_32BGRA</code></li>
<li>输出的是BGRA的格式</li>
</ul></li>
</ul>
<p>Android从摄像头采集的预览数据一般都是NV21，iOS一般采集的数据都是NV12。</p>
<h2 id="参考资料">参考资料</h2>
<ul>
<li><p>https://juejin.im/post/5a572730f265da3e2c3803ad</p></li>
<li><p><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/YUV">YUV - Wikipedia</a></p></li>
<li><p><a target="_blank" rel="noopener" href="https://www.fourcc.org/yuv.php">YUV pixel formats</a></p></li>
</ul>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9F%B3%E8%A7%86%E9%A2%91/" rel="tag"># 音视频</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/image_basic_technology/" rel="prev" title="图像基础技术">
      <i class="fa fa-chevron-left"></i> 图像基础技术
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/video_compression_technology/" rel="next" title="视频压缩技术">
      视频压缩技术 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4"><span class="nav-text">色彩空间</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#rgb%E6%A0%BC%E5%BC%8F"><span class="nav-text">RGB格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv%E6%A0%BC%E5%BC%8F"><span class="nav-text">YUV格式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%87%E6%A0%B7%E6%96%B9%E5%BC%8F"><span class="nav-text">采样方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv444"><span class="nav-text">YUV4:4:4</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv422"><span class="nav-text">YUV4:2:2</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv420"><span class="nav-text">YUV4:2:0</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AD%98%E5%82%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">存储格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%83%8F%E7%B4%A0%E6%A0%BC%E5%BC%8F"><span class="nav-text">像素格式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv422-1"><span class="nav-text">YUV422</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#yuv420-1"><span class="nav-text">YUV420</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%A0%E7%94%A8%E5%AD%97%E8%8A%82%E6%95%B0"><span class="nav-text">占用字节数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#yuv%E6%95%B0%E6%8D%AE%E8%AE%BF%E9%97%AE"><span class="nav-text">YUV数据访问</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ios%E7%9B%B8%E6%9C%BA%E6%94%AF%E6%8C%81%E8%BE%93%E5%87%BA%E5%9B%BE%E7%89%87%E6%A0%BC%E5%BC%8F"><span class="nav-text">iOS相机支持输出图片格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-text">参考资料</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
          load: ['[tex]/mhchem'],
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
          packages: {'[+]': ['mhchem']},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : 'ebaefafca86672c76f4744550476850d',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
